package com.pe1n.yangtaopai.view.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.drm.DrmInfoRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.pe1n.yangtaopai.R;
import com.pe1n.yangtaopai.base.BaseFragment;
import com.pe1n.yangtaopai.bean.NetWorkBean;
import com.pe1n.yangtaopai.bean.UpdataNameBean;
import com.pe1n.yangtaopai.customClass.SelectPicPopupWindow;
import com.pe1n.yangtaopai.helper.BitmapCircleTransformation;
import com.pe1n.yangtaopai.view.activity.AddressActivity;
import com.pe1n.yangtaopai.view.activity.CollectActivity;
import com.pe1n.yangtaopai.view.activity.CustomerActivity;
import com.pe1n.yangtaopai.view.activity.FavorableActivity;
import com.pe1n.yangtaopai.view.activity.LogInActivity;
import com.pe1n.yangtaopai.view.activity.OpinionActivity;
import com.pe1n.yangtaopai.view.activity.OrderActivity;
import com.pe1n.yangtaopai.view.activity.RankingActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.text.DecimalFormat;




public class MyFragment extends BaseFragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private Intent intent;
    private static final String ARG_PARAM2 = "param2";
    private LinearLayout mDengLuLinearLayout;//登录
    private LinearLayout mDingDanLinearLayout;//全部订单
    private LinearLayout mFuKuanLinearLayout;//代付款
    private LinearLayout mFaHuoLinearLayout;//待发货
    private LinearLayout mDShouHuoLinearLayout;//待收货
    private LinearLayout mYShouHuoLinearLayout;//已收货
    private LinearLayout mYouHuiLinearLayout;//优惠卷
    private LinearLayout mDiZhiLinearLayout;//收货地址
    private LinearLayout mKeFuLinearLayout;//客服
    private LinearLayout mShoppLinearLayout;//商品
    private TextView mTextView;
    private LinearLayout mJieShaoLinearLayout;//介绍
    private LinearLayout mBandDanLinearLayout;//榜单
    private LinearLayout mClearLinearLayout;//清除缓存
    private LinearLayout mYiJianLinearLayout;//意见反馈
    private LinearLayout mPingFenLinearLayout;//去评分
    private Context mContext;
    private SharedPreferences sharedPreferences;
    private long filesize=0;
    private TextView mTextViewCache;
    private String cacheSize="0kB";
    public static boolean isNet;//证明已有网
    private ImageView  imgeView;   //myFragment_touXiangIma
    // TODO: Rename a  nd change types of parameters
    private String mParam1;
    private String mParam2;
    private Activity activity;
    public MyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyFragment newInstance(String param1, String param2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity= (Activity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mContext=getContext();

        return inflater.inflate(R.layout.fragment_my, container, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.myFragment_main_dengLu:
                //判断是否注册或登录了,一个布尔值存入.xml文件中了
                sharedPreferences=mContext.getSharedPreferences("myshared",0);
                boolean boo=sharedPreferences.getBoolean("isRegister",false);
                if(!boo){
                    SelectPicPopupWindow selectPicPopupWindow=new SelectPicPopupWindow(mContext,sharedPreferences);
                    selectPicPopupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
                }
                else{
                    Intent intent=new Intent(mContext,LogInActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.myFragment_main_all_dingDan:
                intent.setClass(mContext, OrderActivity.class);
                intent.putExtra("VP_INDEX",0);
                startActivity( intent);
                break;
            case R.id.myFragment_main__daiFuKuan:
                intent.setClass(mContext, OrderActivity.class);
                intent.putExtra("VP_INDEX",1);
                startActivity( intent);
                break;
            case R.id.myFragment_main__daiFaHuo:
                intent.setClass(mContext, OrderActivity.class);
                intent.putExtra("VP_INDEX",2);
                startActivity( intent);
                break;
            case R.id.myFragment_main__daiShouHuo:
                intent.setClass(mContext, OrderActivity.class);
                intent.putExtra("VP_INDEX",3);
                startActivity( intent);
                break;
            case R.id.myFragment_main__yiShouHuo:
                intent.setClass(mContext, OrderActivity.class);
                intent.putExtra("VP_INDEX",4);
                startActivity( intent);
                break;
            case R.id.myFragment_main_youHuiJuan:
                intent.setClass(mContext, FavorableActivity.class);
                startActivity( intent);
                break;
            case R.id.myFragment_main__shouHuoDiZhi:
                intent.setClass(mContext, AddressActivity.class);
                startActivity( intent);
                break;
            case R.id.myFragment_main_jieShao :
                Intent intent1=new Intent();
                intent1.setAction(Intent.ACTION_PICK);
                intent1.setData(Contacts.People.CONTENT_URI);
                startActivity( intent1);
                break;
            case R.id.myFragment_main_shangPin:
                intent.setClass(mContext, CollectActivity.class);
                startActivity( intent);
                break;
            case R.id.myFragment_main_keFu:
                if(MyFragment.isNet){
                    intent.setClass(mContext, CustomerActivity.class);
                    startActivity( intent);
                }
                else{
                    //View view= LayoutInflater.from(mContext).inflate(R.layout.not_net_layout,null,false);
                   // PopupWindow popupWindow=new PopupWindow( view, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                    //popupWindow.setOutsideTouchable(true);
                   // popupWindow.showAtLocation(view, Gravity.CENTER,0,0);
                    Toast.makeText(mContext,"网络连接失败",Toast.LENGTH_LONG).show();

                }
                break;
            case R.id.myFragment_main__bangDan:
                intent.setClass(mContext, RankingActivity.class);
                startActivity( intent);
                break;
            case R.id.myFragment_main_clear:
                mTextViewCache.setText("0MB");
                new Thread(){
                    public void run(){
                         clearCacheFolder(mContext.getFilesDir(),System.currentTimeMillis());
                         clearCacheFolder(mContext.getCacheDir(),System.currentTimeMillis());
                    }
                }.start();
                break;
            case R.id.myFragment_main_yiJian:
                intent.setClass(mContext, OpinionActivity.class);
                startActivity( intent);
                break;
            case R.id.myFragment_main_quPingFen:

                break;
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        intent=new Intent();
        mJieShaoLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_jieShao);
        mJieShaoLinearLayout.setOnClickListener(this);
        imgeView= (ImageView) view.findViewById(R.id.myFragment_touXiangIma);
        mTextViewCache= (TextView) view.findViewById(R.id.fragment_my_textView_cache1);
        mTextView= (TextView) view.findViewById(R.id.myFragment_name_textView);
        mDengLuLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_dengLu);
        mDengLuLinearLayout.setOnClickListener(this);
        mDingDanLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_all_dingDan);
        mDingDanLinearLayout.setOnClickListener(this);
        mFuKuanLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__daiFuKuan);
        mFuKuanLinearLayout.setOnClickListener(this);
        mFaHuoLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__daiFaHuo);
        mFaHuoLinearLayout.setOnClickListener(this);
        mDShouHuoLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__daiShouHuo);
        mDShouHuoLinearLayout.setOnClickListener(this);
        mYShouHuoLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__yiShouHuo);
        mYShouHuoLinearLayout.setOnClickListener(this);
        mYouHuiLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_youHuiJuan);
        mYouHuiLinearLayout.setOnClickListener(this);
        mDiZhiLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__shouHuoDiZhi);
        mDiZhiLinearLayout.setOnClickListener(this);
        mShoppLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_shangPin);
        mShoppLinearLayout.setOnClickListener(this);
        mKeFuLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_keFu);
        mKeFuLinearLayout.setOnClickListener(this);
        mBandDanLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main__bangDan);
        mBandDanLinearLayout.setOnClickListener(this);
        mClearLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_clear);
        mClearLinearLayout.setOnClickListener(this);
        mYiJianLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_yiJian);
        mYiJianLinearLayout.setOnClickListener(this);
        mPingFenLinearLayout= (LinearLayout) view.findViewById(R.id.myFragment_main_quPingFen);
        mPingFenLinearLayout.setOnClickListener(this);
    }



    @Subscribe(sticky = true)
    public void  onMessageEvent(NetWorkBean netWorkBean){
        isNet=netWorkBean.isCollectNet();
    }
    @Subscribe(sticky = true)
    public void  onUpdataName(UpdataNameBean updataNameBean){
        mTextView.setText( updataNameBean.getName());
        String path=updataNameBean.getPath();
        if(path!=null) {
            Glide.with(mContext)
                    .load(path)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new BitmapCircleTransformation(mContext))
                    .into(imgeView);

        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        File filesDir=mContext.getFilesDir();
        File cacheDir=mContext.getCacheDir();
        //得到缓存
        filesize+=getDirSize(filesDir);
        filesize+=getDirSize(cacheDir);
        cacheSize=formatFileSize( filesize);
        mTextViewCache.setText(cacheSize);
        //SD卡会有缓存.啦啦
        //final boolean methodsCompat = isMethodsCompat(Build.VERSION_CODES);
        //sharedPreferences.edit().putBoolean("isRegister",false).commit();
        File file=new File(Environment.getExternalStorageDirectory(),"my_image.jpg");
        if(file.exists()){
            Glide.with(mContext)
                    .load(file)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new BitmapCircleTransformation(mContext))
                    .into(imgeView);

        }
        else {
            Glide.with(mContext)
                    .load(R.mipmap.touxiang)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new BitmapCircleTransformation(mContext))
                    .into(imgeView);
        }
        SharedPreferences sharedPreferences=mContext.getSharedPreferences("myshared",0);
        String string=sharedPreferences.getString("niCheng","登录");
        mTextView.setText(string);
        }

    public  boolean isMethodsCompat(int VersionCode) {
        int currentVersion= Build.VERSION.SDK_INT;
        Log.e(" currentVersion",String.valueOf(currentVersion));
        return currentVersion>=VersionCode;
    }

    public static long getDirSize(File dir) {
        if( dir==null){
            return 0;
        }
        if(!dir.isDirectory()){
            return 0;
        }
        long dirSize=0;
        File[]files=dir.listFiles();
        for(File file:files){
            if(file.isFile()){
            dirSize+=file.length();
            }
            else if(file.isDirectory()){
                dirSize+=file.length();
                dirSize+=getDirSize(file);
            }

        }
      return dirSize;
    }
    public String formatFileSize(long files){
        DecimalFormat df=new DecimalFormat();
        String fileSize="";
        if(files<1024){
            fileSize=df.format((double)files)+"B";
        }else if(files<1048576){
            fileSize=df.format((double)files/1024)+"KB";
        }else if(files<1073741824){
            fileSize=df.format((double)files/1048576)+"MB";

        }
        return fileSize;
    }

 //清除缓存
    public int clearCacheFolder(File dir,long curTime){
        int deleteFiles=0;
        if( dir!=null&&dir.isDirectory()){
            for(File child:dir.listFiles()){
                if(child.isDirectory()){
                    deleteFiles+=clearCacheFolder(child,curTime);
                }
                if(child.lastModified()<curTime){
                    if(child.delete()){
                        deleteFiles++;
                    }
                }
            }
        }
        return deleteFiles;
    }
}

